package tests;

import static org.junit.Assert.*;

import java.util.Iterator;
import java.util.List;

import model.MediaProperty;
import model.filemanager.FileManager;
import model.filemanager.MediaList;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import view.MediaFormatTypeEnum;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;

public class MediaListTest {
	
	String listName = "testList";
	String type = "audio";
	String type2 = "video";
	String user = "testuser@test.com";
	FileManager fm = new FileManager(user);
	String [] mediaKeys = {"testkey1","testkey2","testkey3"};
	
	long listKey;
	
	private final LocalServiceTestHelper helper =
	            new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
	
	@Before
	public void setUp() {
		helper.setUp();	
	}
	
	@After
	public void tearDown() {
		helper.tearDown();
	}
	
	@Test
	public void testAddList(){
		listKey = MediaList.AddList(listName, type, user);
		assertEquals(listKey, MediaList.getListKey(listName, type, user));
	}
	
	@Test
	public void testRemoveList(){
		testAddList();
		MediaList.RemoveList(listKey);
		assertEquals(-1, MediaList.getListKey(listName, type, user));
	}
	
	@Test
	public void testAddMedia(){
		testAddList();
		for(int i=0;i<mediaKeys.length;i++){
			MediaList.addMedia(listKey, mediaKeys[i]);
		}
	}
	
	@Test
	public void testGetMedia(){
		testAddMedia();
		
		List<Entity> listMedia = MediaList.getMedia(listKey);
		Iterator<Entity> iter = listMedia.iterator();
		while(iter.hasNext()){
			Entity mediaEntity = (Entity) iter.next();
			boolean keyFound = false;
			for(int i=0;i<mediaKeys.length;i++){ // search in the keys list
				keyFound |= mediaKeys[i].equals(mediaEntity.getProperty("mediakey"));
			}
			assertTrue("key was not found", keyFound);
		}
	}
	
	
	@Test
	public void testRemoveMedia(){
		testAddMedia();
		
		for(int i=0;i<mediaKeys.length;i++){
			MediaList.removeMedia(listKey, mediaKeys[i]);
		}
		
		List<Entity> listMedia = MediaList.getMedia(listKey);
		
		assertTrue("media list size was not zero", listMedia.size() == 0);
	}
	
	
	@Test
	public void addMultipleLists(){
		int numLists = 10;
		long[] listKeys = new long[numLists];
		
		for(int i=0;i<numLists;i++){
			if(i%2==0){
				listKeys[i] = MediaList.AddList(listName, i%2==0 ? type : type2, user); // half in each type
			}
		}
		
	}
	
}
